local weihuan = fk.CreateSkill{
  name = "plum__weihuan",
}

Fk:loadTranslationTable{
  ["plum__weihuan"] = "为宦",
  [":plum__weihuan"] = "结束阶段，你可以令一名手牌数不大于你的角色将手牌数调整至X（X为你为偶数的项数：体力值、手牌数、本回合使用牌数）。每回合结束时，若X为偶数，你摸一张牌。",

  ["$plum__weihuan1"] = "卿诸人宜速进道，冀有所达。",
  ["$plum__weihuan2"] = "吾人远辱国命，自弃於此，与死亡何异？",

  ["#plum__weihuan-adjust"] = "为宦：可以令一名角色将手牌数调整至%arg",
}

---@param player ServerPlayer
---@return number
local getEven = function (player)
  local count = 0
  local hp, hand, use = player.hp, #player:getCardIds(Card.PlayerHand), 0

  local logic = player.room.logic
  local use_events = logic:getEventsOfScope(GameEvent.UseCard, 999, function (e) return true end, Player.HistoryTurn)
  for _, e in ipairs(use_events) do
    if e.data.from == player then
      use = use + 1
    end
  end

  for _, num in ipairs {hp, hand, use} do
    if num % 2 == 0 then
      count = count + 1
    end
  end
  return count
end

weihuan:addEffect(fk.EventPhaseStart, {
  anim_type = "drawcard",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill("plum__weihuan") and player == target and player.phase == Player.Finish
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local num = getEven(player)
    local tos = table.filter(room:getAlivePlayers(false), function (p)
      return p:getHandcardNum() <= player:getHandcardNum()
    end)
    local to = room:askToChoosePlayers(player, {
      targets = tos,
      min_num = 1,
      max_num = 1,
      prompt = "#plum__weihuan-adjust:::"..num,
      skill_name = weihuan.name,
      cancelable = true
    })
    if #to == 1 then
      event:setCostData(self, { to = to[1], num = num })
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local d = event:getCostData(self)
    local to, num = d.to, d.num ---@type ServerPlayer, number
    if to:getHandcardNum() == num then
    elseif to:getHandcardNum() > num then
      room:askToDiscard(to, {
        min_num = to:getHandcardNum() - num,
        max_num = to:getHandcardNum() - num,
        skill_name = weihuan.name,
      })
    else
      to:drawCards((num - to:getHandcardNum()), weihuan.name)
    end
  end
})

weihuan:addEffect(fk.TurnEnd, {
  anim_type = "drawcard",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(weihuan.name) and getEven(player) % 2 == 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    player:drawCards(1, weihuan.name)
  end
})

return weihuan